package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ResourcesServiceClient;
import com.hxkj.domain.po.Resources;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ResultDataStruct;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

/**
 * @ClassName LinkResourcesDirective link资源引入标签
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/21 16:13
 * @Version 1.0
 */
@Component
@Log4j
public class LinkResourcesDirective extends AbstractDirective {
    @Autowired
    private ResourcesServiceClient resourcesServiceClient;

    @Value("${cms.realPath}")
    private String Path;

    @Value("${cms.Path}")
    private String cmsPath;

    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，站点ID
     */
    public static final String REL = "rel";

    /**
     * 输入参数，站点ID
     */
    public static final String HREF = "href";

    /**
     * 输出对象
     */
    public static final String RESOURCES_PATH = "t";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws
            TemplateException, IOException {
        try {
            //Mr.zheng:获取参数
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            String rel = super.getString(REL, params) == null ? "" : super.getString(REL, params);
            String href = super.getString(HREF, params) == null ? "" : super.getString(HREF, params);

            if (StringUtils.isEmpty(href)) {
                log.info("请给出资源文件引入条件");
            }

            Resources resources = new Resources();
            String[] st = href.split("/");
            String resourcesName = st[st.length - 1];
            String s = StringUtils.substringBeforeLast(href, "/");
            resources.setResourcesName(resourcesName);
            resources.setSiteId(siteId);
            ResultDataStruct<List<Resources>> resultDataStruct = resourcesServiceClient.getResourcesBySiteId(resources);
            //TODO:返回文件路径待确定
            String path = "";
            if (resultDataStruct.getData() == null) {
                path = "Please give the correct resource file import condition.";
            }
            List<Resources> resourcesList = resultDataStruct.getData();
            for (Resources res : resourcesList) {
                String filename = res.getFileName().concat(res.getResourcesName());
                if (filename.contains(href) && res.getIsDirectory() == 1) {
                    path = res.getPath();
                    break;
                }
            }
            if (StringUtils.isEmpty(path)) {
                //如果未匹配到对应的文件,直接拼接路径查询数据库 处理可视化及生成时问题
                resources = new Resources();
                resources.setSiteId(siteId);
                resources.setPath(href);
                List<Resources> resultDataStruct1 = resourcesServiceClient.selectContainPathFolder(resources);
                if (resultDataStruct1 != null && resultDataStruct1.size() > 0) {
                    Resources resources1 = resultDataStruct1.get(0);
                    if (resources1 != null)
                        path = resources1.getPath();
                }
            }

            String note = super.getNote(env);
            StringBuffer sb = new StringBuffer();
            if (!StringUtils.isEmpty(note))
//                path = "<link rel=\"" + rel + "\"  href=\"" + cmsPath + path + "\" help=\"" + resourcesName + "\"></link>";
                path = sb.append("<link rel=\"").append(rel).append("\"  href=\"").append(cmsPath).append(path).append("\" help=\"").append(resourcesName).append("\"></link>").toString();
            else
//                path = "<link rel=\"" + rel + "\"  href=\"" + Path + path + "\" help=\"" + resourcesName + "\"></link>";
                path = sb.append("<link rel=\"").append(rel).append("\"  href=\"").append(Path).append(path).append("\" help=\"").append(resourcesName).append("\"></link>").toString();

            env.setVariable(RESOURCES_PATH, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(path));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                body.render(env.getOut());
            } else {
                throw new RuntimeException("资源文件所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
